//引入模型
require('./../model/testsModel');
require('./../model/errorsModel');
require('./../model/exercisesModel');
require('./../model/testedsModel')
const mongoose = require('mongoose');

//根据考试类型获取所有的考试
async function getAllTestsByType(req, res, next) {
    let { typeId } = req.body;
    let tests = await mongoose.model('testsModel').find({ typeId: typeId });
    console.log(tests);
    res.send({ data: tests, code: 200 });
}

//交卷,完成考试
async function DoneTest(req, res, next) {
    // let testId = "610bce08a50c00009700644d";
    // let studentId = "610bb559a50c000097006402";
    // let testArr = [0,0,1,1,1];
    

    //从前端获取考题数组，考试id和学生id
    let { testArr, testId, studentId } = req.body;
    //获取当前考试
    let tests = await mongoose.model('testsModel').find({ _id: testId });
    //获取考试的考题
    let testExerArr = tests[0].exercisesId;
    let exercises = await mongoose.model('exercisesModel').find({ _id: testExerArr });
    //试卷总分
    let testScore = 0;
    //学生得分
    let studentScore = 0;
    for (let i = 0; i < exercises.length; i++) {
        testScore += exercises[i].score;
        //如果相等，则题做对
        if (testArr[i] == exercises[i].answer) {
            studentScore += exercises[i].score;
        } else {
            //将错题放入错题集
            await mongoose.model('errorsModel').create({ studentId: studentId, exerciseId: exercises[i]._id, errorAnswer: testArr[i] });
        }
    }
    //在tested中添加一条已考试记录
    await mongoose.model('testedsModel').create({ studentId: studentId, testId: testId, score: studentScore });
    res.send({ testScore, studentScore, testId, code: 200 });
}


module.exports = {
    getAllTestsByType,
    DoneTest
}